import * as api from '@/services/ReturnMoneyPlanMgr';
import _ from 'lodash';
import moment from 'moment';
import { getExpandedRowKeys, buildTree } from '../utils/publicMethod';

const Model = {
  namespace: 'AllReturnMoneyPlan',
  state: {
    currentYear: null,
    overAllYears: [],
    currentMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14'],
    all: [],
    treeData: [],
    expandedRowKeys: [],
  },
  effects: {
    // 年份列表
    *getYearList({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { overAllYears: [], currentYear: null, treeData: [] },
      });
      const response = yield call(api.overallYearListUsingGET, payload);
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        let currentYear = null;
        const isYearValue = _.filter(response.data, x => x === `${moment().year()}`);
        if (!_.isEmpty(isYearValue)) currentYear = _.head(isYearValue);
        yield put({
          type: 'save',
          payload: { overAllYears: response.data, currentYear: currentYear || response.data[0] },
        });
      } else if (callback) callback();
    },
    // 全盘表格数据
    *getTableList({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          all: [],
          treeData: [],
          expandedRowKeys: [],
        },
      });
      const response = yield call(api.overallAnnualDataUsingGET, payload);
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        const all = response.data;
        // 获取展开的列key  筛选过滤 type !== org_build
        const notOrgBuild = _.filter(all, data => data.type !== 'org_build');
        const expandedRowKeys = getExpandedRowKeys(notOrgBuild);
        const treeData = buildTree(all);
        yield put({
          type: 'save',
          payload: { all, treeData, expandedRowKeys },
        });
      }
      if (callback && _.isEmpty(response.data)) callback();
    },
  },
  reducers: {
    changeCurrentYear(state, action) {
      const { currentYear } = action.payload;
      return {
        ...state,
        currentYear,
      };
    },
    changeCurrentMonths(state, action) {
      let { currentMonths } = action.payload;
      if (currentMonths == null || currentMonths.length === 0) {
        currentMonths = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14'];
      }
      return {
        ...state,
        currentMonths,
      };
    },

    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
